package com.okilo.online.app.act

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.R
import com.okilo.online.app.base.app.OkiloActStackManager
import com.okilo.online.app.common.OkiloComAct
import com.okilo.online.app.configs.OkiloConfigs
import com.okilo.online.app.databinding.OkiloActUserLoginBinding
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.event.room.OkiloPointManager
import com.okilo.online.app.tools.OkiloDateUtil
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.extensions.getColorRes
import com.okilo.online.app.tools.helper.OkiloAnalysisHp
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.pet.OkiloUserPet
import com.okilo.online.app.pet.view.IOkiloUser
import com.okilo.online.app.weight.font.OkiloRbtMediumEditText
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class OkiloUserLoginAct : OkiloComAct(), IOkiloUser.IOkiloUserLogin {
    lateinit var binding: OkiloActUserLoginBinding
    private var uLoginPet: OkiloUserPet? = null

    override val pageName: String = "Login_Page"

    override fun createOkiloContentView(): View {
        binding = OkiloActUserLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeOkiloViews() {
        getTitleBarManager()
            .setTitleBarVisibility(View.GONE)
            .setRootBackgroundColor(getColor(R.color.okilo_color_white))
            .setTitleVisibility(View.GONE)
            .setBackButtonVisibility(View.GONE)
            .setRightButtonVisibility(View.GONE)
        //关闭所有页面
        OkiloActStackManager.finishAllActivity(OkiloUserLoginAct::class.java)
        cOkiloLoginBtnState()
    }

    override fun setupOkiloEventListeners() {
        super.setupOkiloEventListeners()
        binding.okiloULogTextMobile.setOnClickListener (object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_LOGIN_SELF_MOBILE)
                gOkiloSelfPhoneNumber()
            }
        })
        binding.okiloULogEditMobile.setInputFocusChangeListener(object : OkiloRbtMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                cOkiloLoginBtnState(hasFocus)
            }
            override fun onCompleteAction(v: View?, remark: String?) {
                addEventPointRequestAction(OkiloEventPointType.OKILO_FORM_TRACK.LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.okiloULogEditMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (gOkiloUserLoginMobile().isNotEmpty()) {
                    binding.okiloULogEditMobile.setTextColor(getColor(R.color.okilo_color_black))
                }
                cOkiloLoginBtnState(true)
            }
        })
        binding.okiloULogEditMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.okiloULogEditMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.okiloULogCheckBox.setOnCheckedChangeListener { _, isChecked ->
            cOkiloLoginBtnState(true)
            when (isChecked) {
                true -> {
                    addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOGIN_PRIVACY_AGREE)
                }

                false -> {
                    addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.okiloULogButtonNext.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                binding.okiloULogEditMobile.clearFocus()
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.LOGIN_NEXT, gOkiloUserLoginMobile())
                onHideSoftInput(binding.okiloULogEditMobile)
                // TODO: 登录注册点下一步 需上报所有埋点
                OkiloPointManager.getInstance().manualReport()

                if (uLoginPet == null){
                    uLoginPet = OkiloUserPet(this@OkiloUserLoginAct)
                }
                showOkiloLoading()
                uLoginPet?.gOkiloUserLoginRequest(this@OkiloUserLoginAct)
            }
        })

        //隐私协议
        binding.okiloULogPP.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                val showTitle = getString(R.string.okilo_privacy_policy)
                val linkUrl = OkiloConfigs.OKILO_PP_NIGERIA_LINK
                OkiloPrivacyPolicyAct.start(this@OkiloUserLoginAct, showTitle, linkUrl)
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun loadOkiloData() {
        val showZoneCode = "+${OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_TIMEZONE_CODE)}"
        binding.okiloULogZoneCode.text = showZoneCode

        val showPrivacyPolicy = String.format(getString(R.string.okilo_ulog_privacy_policy), getString(
            R.string.okilo_privacy_policy))
        val privacyPolicySpannable = SpannableString(showPrivacyPolicy)
        val startIndex = showPrivacyPolicy.indexOf(getString(R.string.okilo_privacy_policy))
        privacyPolicySpannable.setSpan(ForegroundColorSpan(getColorRes(R.color.okilo_color_black)), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        privacyPolicySpannable.setSpan(UnderlineSpan(), startIndex, showPrivacyPolicy.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.okiloULogPP.text = privacyPolicySpannable

        binding.okiloULogEditMobile.visibility = View.VISIBLE
        binding.okiloULogTextMobile.visibility = View.VISIBLE
    }

    /**
     * 设置登录按钮状态
     */
    private fun cOkiloLoginBtnState(hasFocus: Boolean = false) {
        binding.okiloULogEditMobile.setTextColor(getColor(R.color.okilo_color_black))
        binding.okiloULogButtonNext.isEnabled = binding.okiloULogCheckBox.isChecked && gOkiloUserLoginMobile().isNotEmpty()
    }

    /**
     * 获取本机手机号码
     */
    private fun gOkiloSelfPhoneNumber(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    iOkiloHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    OkiloLog.e("Launching the PendingIntent failed")
                    sOkiloEditInputMobile()
                }
            }
            .addOnFailureListener {
                OkiloLog.e("Phone Number Hint failed : OnFailureListener")
                sOkiloEditInputMobile()
            }
    }

    private val iOkiloHintIntentResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            OkiloLog.i(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            addEventPointRequestAction(OkiloEventPointType.OKILO_FORM_TRACK.USER_LOGIN_SELF_MOBILE,phoneNumber)
            //时区区号
            val zoneCode = "+${OkiloSharedHp.gOkiloSharedString(OkiloSharedKey.SP_OKILO_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.okiloULogEditMobile.setText(phoneNumber)
            binding.okiloULogEditMobile.visibility = View.VISIBLE
            binding.okiloULogTextMobile.visibility = View.GONE
            binding.okiloULogEditMobile.requestFocus()
            binding.okiloULogEditMobile.setSelection(gOkiloUserLoginMobile().length)
        } catch(e: Exception) {
            OkiloLog.e("Phone Number Hint failed：${e.message}")
            addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.USER_LOGIN_SELF_MOBILE_CANCEL,e.message)
            sOkiloEditInputMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun sOkiloEditInputMobile(){
        binding.okiloULogEditMobile.visibility = View.VISIBLE
        binding.okiloULogTextMobile.visibility = View.GONE

        lifecycleScope.launch {
            delay(200)
            binding.okiloULogEditMobile.requestFocus()
            onShowSoftInput(binding.okiloULogEditMobile)
            binding.okiloULogEditMobile.setSelection(gOkiloUserLoginMobile().length) // 将光标设置到文本末尾
        }
    }

    private fun sOkiloMainPage() {
        onIntent(OkiloMainAct::class.java)
        finish()
    }

    /**
     * 获取手机号码
     */
    override fun gOkiloUserLoginMobile(): String {
        return binding.okiloULogEditMobile.text.toString().trim()
    }

    /**
     * 登录成功
     */
    override fun sOkiloUserLoginCallback(uid: String, uToken: String) {
        hideOkiloLoading()
        //保存手机号码，个人中心使用
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_MOBILE, gOkiloUserLoginMobile())
        //保存用户登录时间
        val loginTime = OkiloDateUtil.getFormatTime(System.currentTimeMillis(),"dd/MM/yyyy HH:mm:ss")
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_LOGIN_TIME,loginTime)
        //保存用户登录状态为已登录
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_LOGIN,true)
        //保存用户id
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_USERID,uid)
        //保存用户Token
        OkiloSharedHp.sOkiloSharedData(OkiloSharedKey.SP_OKILO_TOKEN, uToken)
        //初始化analysis lib 赋值 用户id 和 token
        OkiloAnalysisHp.initLibAtLoginSuccess(OkiloApplication.Companion.app)
        //进入主页
        sOkiloMainPage()
    }
}